package com.nhn.android.samples.oauth;


import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.eventpopup.R;
import com.nhn.android.samples.network.HttpOAuthSessionSample;
import com.nhn.android.samples.network.HttpSessionHandler;
import com.nhn.android.samples.webview.WebViewDialog;

public class ThirdPartyOAuthSampleActivity extends Activity {
    /** Called when the activity is first created. */
	
	final public static String AUTH_TOKEN = "AUTH_TOKEN";
	final public static String AUTH_PIN = "AUTH_PIN";

	
	final private static String CONSUMER_KEY = "KhArzRyRcNkZ";
	final private static String CONSUMER_SECRET = "50737672VVyYpFdsODMC";

	final private static String REQUEST_TOKEN_ENDPOINT_URL = "https://nid.naver.com/naver.oauth?mode=req_req_token";
	final private static String ACCESS_TOKEN_ENDPOINT_URL = "https://nid.naver.com/naver.oauth?mode=req_acc_token";
	final private static String AUTHORIZATION_WEBSITE_URL = "https://nid.naver.com/naver.oauth?mode=auth_req_token";
	
	OAuthConsumer mConsumer = null;
	OAuthProvider mProvider = null;
	
	private String mAccessToken = "";
	private String mAccessSecret = "";
	private String mPIN = "";
	
	Button mAuthButton = null;
	Button mGetButton = null;
	Button mPostButton = null;
	Button mPutButton = null;
	Button mDeleteButton = null;
	Button mClearButton = null;
	TextView mResultText = null;
	
	private Handler handler = null;
	WebViewDialog  mDialog = null;
	
	//API 요청후 받는 결과 리스너
	HttpSessionHandler mSessionHandler = new HttpSessionHandler() {
		
		public void onResult(int resultCode, final Object param) {
			if (resultCode == 200) {
				mResultText.post(new Runnable() {
					
					public void run() {
						mResultText.setText((String)param);
					}
				});
				
			} else {
				mResultText.post(new Runnable() {
					
					public void run() {
						mResultText.setText("서버연결 실패");
					}
				});
			}
		}
		
		public void onProgress(int resultCode, Object param) {
		}
	};
	
	


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 100) {

					mDialog.dismiss();
					mDialog = null;
					mPIN = (String) msg.obj;
			
					try {
						getAccessToken(mPIN);
						
						if (mAuthButton != null) {
							mAuthButton.setText("재인증하기");
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				super.handleMessage(msg);
			}
        		
        };
        
        
        mConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        	mProvider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_ENDPOINT_URL, ACCESS_TOKEN_ENDPOINT_URL, AUTHORIZATION_WEBSITE_URL);

        	mAuthButton = (Button) findViewById(R.id.oauth_button);
        	mGetButton = (Button) findViewById(R.id.api_get_button);
        	mPostButton = (Button) findViewById(R.id.api_post_button);
        	mPutButton = (Button) findViewById(R.id.api_put_button);
        	mDeleteButton = (Button) findViewById(R.id.api_delete_button);
        	mClearButton = (Button) findViewById(R.id.clear_button);
        	
        	mResultText = (TextView) findViewById(R.id.result_text);
        	
        	mAuthButton.setOnClickListener(clickListener);
        	mGetButton.setOnClickListener(clickListener);
        	mPostButton.setOnClickListener(clickListener);
        	mPutButton.setOnClickListener(clickListener);
        	mDeleteButton.setOnClickListener(clickListener);
        	mClearButton.setOnClickListener(clickListener);

        	SharedPreferences sh = getSharedPreferences("ACCESS_TOKEN", Activity.MODE_PRIVATE);
        	mAccessToken = sh.getString("key_access_token", "");
        mAccessSecret = sh.getString("key_access_secret", "");

        mConsumer.setTokenWithSecret(mAccessToken, mAccessSecret);
       
        if (TextUtils.isEmpty(mAccessToken) == false && TextUtils.isEmpty(mAccessSecret) == false ) {
        		mAuthButton.setText("재인증하기");
        }
        
        
    }
    
    OnClickListener clickListener = new OnClickListener() {
		
		public void onClick(View v) {
			Button view = (Button)v;
			String label = (String) view.getText();

	   	 	try {
	   	 		if (label.equalsIgnoreCase("인증하기") || label.equalsIgnoreCase("재인증하기")) {
	   	 			oAuthRequest();
	   	 		} else if (label.equalsIgnoreCase("GET") ) {
	   	 			requestUrlGet();
	   	 		} else if (label.equalsIgnoreCase("POST") ) {
	   	 			requestUrlPost();
	   	 		} else if (label.equalsIgnoreCase("PUT") ) {
	   	 			requestUrlPut();
	   	 		} else if (label.equalsIgnoreCase("DELETE") ) {
	   	 			requestUrlDelete();
	   	 		} else if (label.equalsIgnoreCase("인증초기화") ) {
	   	 			//결과 지우기
					mResultText.post(new Runnable() {
						public void run() {
							mResultText.setText((String)"");
							mAuthButton.setText("인증하기");
						}
					});
					
					mConsumer.setTokenWithSecret("", "");
					mAccessToken = "";
					mAccessSecret = "";
	   	 		}
	   	 		
				
			} catch (Exception e) {
				e.printStackTrace();
				finish();
			}
		}
	};
    
	//token 요청
    public void oAuthRequest() throws Exception {
	 	String authUrl = mProvider.retrieveRequestToken(mConsumer,OAuth.OUT_OF_BAND );
	 	mDialog = new WebViewDialog(this);
	 	mDialog.loadUrl(authUrl);
	 	mDialog.setJobCompleteListener(handler);
	 	mDialog.setOnClickListener(new com.nhn.android.samples.webview.DialogButtonClickListener() {
			public void onClick(View view) {
				mDialog.dismiss();
			}
		});
	 	mDialog.show();
    	 
    }
   
    //access token 요청
    public void getAccessToken(String PIN) throws Exception {
    		mProvider.retrieveAccessToken(mConsumer, PIN);
    		mAccessToken = mConsumer.getToken();
    		mAccessSecret = mConsumer.getTokenSecret();
    		SharedPreferences sh = getSharedPreferences("ACCESS_TOKEN", Activity.MODE_PRIVATE);
    		SharedPreferences.Editor ed = sh.edit();
    		ed.putString("key_access_token", mAccessToken);
    		ed.putString("key_access_secret", mAccessSecret);
    		ed.commit();
    }
    
    //get방식 테스트 시작
    public boolean requestUrlGet() throws Exception {
    		String urlPage = "http://opensocial.apis.naver.com/rest/people/@viewer/@friends?startIndex=0&count=6&filterBy=hasApp&filterValue=true&format=xml";
    		//String urlPage = "http://dev.opensocial.apis.naver.com/rest/appdata/@viewer/@self";
    		HttpOAuthSessionSample httpSession = new HttpOAuthSessionSample(mSessionHandler,mConsumer);
    		httpSession.create(HttpOAuthSessionSample.METHOD_GET);
    		httpSession.setViewer("");
    		httpSession.open(urlPage);
    		return true;
    }
    
    //post방식 테스트 시작
    public boolean requestUrlPost() throws Exception {
    		String urlPage = "http://opensocial.apis.naver.com/rest/appdata/@viewer/@self";
		HttpOAuthSessionSample httpSession = new HttpOAuthSessionSample(mSessionHandler,mConsumer);
		httpSession.create(HttpOAuthSessionSample.METHOD_POST);
		httpSession.setContentType(HttpOAuthSessionSample.CONTENT_TYPE_XML);
		httpSession.setViewer("");
		httpSession.open(urlPage);
		return true;
    }
    
    //put방식 테스트 시작
    public boolean requestUrlPut() throws Exception {
    		String urlPage = "http://opensocial.apis.naver.com/rest/appdata/@viewer/@self";
		HttpOAuthSessionSample httpSession = new HttpOAuthSessionSample(mSessionHandler,mConsumer);
		httpSession.create(HttpOAuthSessionSample.METHOD_PUT); 
		httpSession.setContentType(HttpOAuthSessionSample.CONTENT_TYPE_XML);
		httpSession.setViewer("");
		httpSession.open(urlPage);
		return true;
    }
    
    //delete방식 테스트 시작
    public boolean requestUrlDelete() throws Exception {
    	String urlPage = "http://opensocial.apis.naver.com/rest/appdata/@viewer/@self";	
		HttpOAuthSessionSample httpSession = new HttpOAuthSessionSample(mSessionHandler,mConsumer);
		httpSession.create(HttpOAuthSessionSample.METHOD_DELETE); // 0 is GET
		httpSession.setViewer("");
		httpSession.open(urlPage);
		return true;
    }
    
}